<template>
  <div class="container">
    <div class="container-content">
      <vab-query-form>
        <vab-query-form-top-panel>
          <el-form
            ref="queryRef"
            :model="data.queryForm"
            :inline="true"
            label-width="80"
            label-suffix=""
            @keyup.enter="queryTableData"
          >
            <el-form-item prop="groupId" label="工单分组">
              <DictSelect
                v-model:defaultValue="data.queryForm.groupId"
                placeholder="请选择工单分组"
                dict-code="order_flow_group"
                show-all="Y"
                @change="handleGroupChange"
              />
            </el-form-item>
            <el-form-item prop="groupId" label="工单状态">
              <DictSelect
                v-model:defaultValue="data.queryForm.status"
                placeholder="请选择工单分组"
                dict-code="order_status"
                show-all="Y"
                @change="handleStatusChange"
              />
            </el-form-item>
            <el-form-item prop="flowKey" label="流程Key">
              <CommonSelect
                v-model:defaultValue="data.queryForm.flowKey"
                placeholder="请输入流程名称后检索并选择"
                label="flowFullName"
                value="flowKey"
                url="/esflow/def/get/latest/list"
              />
            </el-form-item>
            <el-form-item prop="formName" label="表单名称">
              <CommonSelect
                v-model:defaultValue="data.queryForm.formName"
                :placeholder="translate('flow.def.formName')"
                label="flowName"
                value="id"
                url="/esflow/form/getlist"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                icon="Refresh-left"
                type="warning"
                @click="handleResetQuery"
                >{{ translate("buttons.reset") }}</el-button
              >
              <el-button icon="search" type="primary" @click="queryTableData">
                {{ translate("buttons.search") }}
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-top-panel>
        <vab-query-form-left-panel>
          <el-button
            v-auth="['taskorder/xz']"
            icon="circle-plus"
            type="primary"
            @click="handleAdd"
            >添加</el-button
          >
        </vab-query-form-left-panel>
      </vab-query-form>
      <el-tabs
        ref="tabs"
        v-model="data.active"
        stretch
        type="border-card"
        @tab-click="handleTabsChange"
      >
        <el-tab-pane
          v-for="(item, index) in data.tabsData"
          :key="index"
          :label="item.dictText"
          :name="item.dictValue"
        />
      </el-tabs>
      <el-row :span="24" :gutter="10">
        <el-col v-for="(item, index) in data.tableData" :key="index" :span="6">
          <div class="card-container">
            <el-card :body-style="{ padding: '5px' }" shadow="never">
              <template #header>
                <div class="card-header">
                  <div
                    style="
                      display: flex;
                      justify-content: start;
                      align-items: center;
                    "
                  >
                    <IconifyIconOnline
                      v-if="item.icon"
                      :icon="item.icon.name"
                      :style="{
                        background: item.icon.bgc,
                        color: item.icon.color
                      }"
                    />
                    {{ item.orderName }}
                  </div>
                  <div>
                    <el-tag
                      :type="item.status === '1' ? 'success' : 'primary'"
                      >{{ item.statusDesc }}</el-tag
                    >
                  </div>
                </div>
              </template>
              <div class="card-content">
                <div class="avue-card__info" v-if="item.defFlow">
                  流程：[V{{ item.defFlow.version }}]{{ item.defFlow.flowName }}
                </div>
                <div class="avue-card__info" v-if="item.defFlow">
                  表单：{{ item.defFlow.formName }}
                </div>
                <div class="avue-card__info">备注：{{ item.remark }}</div>
              </div>
              <template #footer>
                <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    flex-wrap: wrap;
                  "
                >
                  <el-button
                    v-auth="['taskorder/xg']"
                    type="warning"
                    @click.stop="handleEdit(item)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    v-auth="['taskorder/sc']"
                    type="danger"
                    @click.stop="handleDelete(item.id)"
                  >
                    删除
                  </el-button>
                  <el-button
                    v-if="item.defFlow && item.defFlow.id"
                    type="success"
                    @click.stop="openViewFlowPhoto(item)"
                    >流程图</el-button
                  >
                  <el-button
                    v-if="item.defFlow && item.defFlow.status === '1'"
                    type="primary"
                    @click.stop="handleInitiateOrder(item)"
                  >
                    发起
                  </el-button>
                </div>
              </template>
            </el-card>
          </div>
        </el-col>
      </el-row>
      <el-dialog
        v-model="data.showStartForm"
        width="70%"
        top="5vh"
        title="发起工单"
        append-to-body
      >
        <StartForm
          :order="data.order"
          :form="data.form"
          :readonly="false"
          :dialog="true"
          @close="data.showStartForm = false"
          @started="data.showStartForm = false"
          @saved="data.showStartForm = false"
        />
      </el-dialog>
      <el-dialog
        v-model="data.showFlowPic"
        width="60%"
        top="5vh"
        title="流程图"
        append-to-body
      >
        <FlowPhoto
          v-if="data.showFlowPic"
          :def-flow-id="data.order.defFlowId"
          @close="data.showFlowPic = false"
        />
      </el-dialog>
    </div>
    <form-dialog ref="formDialogRef" @refresh="queryTableData" />
  </div>
</template>

<script setup lang="ts" name="TaskOrder">
import * as orderFlow from "@/api/flow/order";
import * as dict from "@/api/admin/system/dict";
import { translate } from "@/plugins/i18n";
import { useMessage, useMessageBox } from "@/hooks/message";
import { validateNull } from "@/utils/validate";
import { TabsPaneContext } from "element-plus";
import DictSelect from "@/components/dictSelect.vue";
import CommonSelect from "@/components/commonSelect.vue";
import StartForm from "./startForm.vue";
import FormDialog from "./form.vue";
// 引入组件
const FlowPhoto = defineAsyncComponent(
  () => import("@/components/flow/flowPhoto.vue")
);
const data = reactive({
  tableData: [],
  tabsData: [],
  showFlowPic: false,
  showStartForm: false,
  order: {
    orderId: "",
    defFlowId: "",
    flowKey: "",
    formId: ""
  },
  form: {
    id: "",
    formName: "",
    formInfo: null,
    printInfo: null,
    componentUrl: ""
  },
  queryForm: {
    flowKey: "",
    formName: "",
    status: "ALL",
    groupId: "ALL"
  },
  active: "-1"
});

const queryRef = ref(null);
const formDialogRef = ref(null);

function queryFlowTabs() {
  dict.queryEntryList({ dictCode: "order_flow_group" }).then(res => {
    data.tabsData = res.data;
    data.active = null;
    if (!validateNull(data.tabsData)) {
      queryTableData(data.queryForm);
    }
  });
}

const queryTableData = (params?: Object) => {
  console.log("active", data.active);
  if (params) {
    Object.assign(data.queryForm, {}, params);
  }
  orderFlow.queryList(data.queryForm).then(response => {
    data.tableData = response.data;
  });
};

const handleResetQuery = () => {
  queryRef.value.resetFields();
  data.active = null;
  data.queryForm = {
    flowKey: "",
    formName: "",
    status: "ALL",
    groupId: "ALL"
  };
  queryTableData(data.queryForm);
};

const handleGroupChange = val => {
  data.queryForm.groupId = val;
  data.active = val;
  queryTableData(data.queryForm);
};

const handleStatusChange = val => {
  data.queryForm.status = val;
  queryTableData(data.queryForm);
};

const handleAdd = () => {
  formDialogRef.value.show("add");
};

const handleEdit = row => {
  formDialogRef.value.show("edit", row);
};

const handleDelete = async ids => {
  useMessageBox()
    .confirm("此操作将永久删除")
    .then(async () => {
      orderFlow.delObjs(ids).then(({ code, msg }) => {
        if (code === 200) {
          queryTableData();
          useMessage().success("删除成功");
        } else {
          useMessage().error(msg);
        }
      });
    });
};

const initDataOrder = item => {
  data.order.orderId = item.id;
  data.order.defFlowId = item.defFlowId;
  data.order.flowKey = item.flowKey;
  if (item.defFlow.flowForm) {
    data.order.formId = item.defFlow.flowForm.id;
    data.form.id = item.defFlow.flowForm.id;
    data.form.formName = item.defFlow.flowForm.formName;
    data.form.formInfo = item.defFlow.flowForm.formInfo;
    data.form.printInfo = item.defFlow.flowForm.printInfo;
    data.form.componentUrl = item.defFlow.flowForm.componentUrl;
  }
};

const handleInitiateOrder = async item => {
  if (!item) {
    data.showStartForm = false;
    return;
  }
  initDataOrder(item);
  data.showStartForm = true;
};

function openViewFlowPhoto(item) {
  data.order = {
    orderId: "",
    defFlowId: "",
    flowKey: "",
    formId: ""
  };
  initDataOrder(item);
  data.showFlowPic = true;
}

function handleTabsChange(tab: TabsPaneContext) {
  data.queryForm.groupId = tab.paneName + "";
  queryTableData(data.queryForm);
}

onMounted(() => {
  queryFlowTabs();
});
</script>

<style lang="scss" scoped>
.card-content {
  height: 100px !important;
  min-height: 100px !important;
  overflow: auto;
}

.container {
  :deep() {
    .el-tabs__content {
      padding-top: 5px !important;
    }
  }
}
</style>
